package cn.iocoder.yudao.module.system.framework.examscore.template.impl;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.system.controller.admin.examscore.vo.ExamScoreImportExcelVO;
import cn.iocoder.yudao.module.system.framework.examscore.config.ExamScoreTemplateProperties;
import cn.iocoder.yudao.module.system.framework.examscore.template.ExamScoreTemplateDataSource;
import com.alibaba.excel.EasyExcel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 外部文件成绩导入模板数据源实现类
 *
 * @author 芋道源码
 */
@Component
@Slf4j
public class FileExamScoreTemplateDataSource implements ExamScoreTemplateDataSource {

    @Resource
    private ExamScoreTemplateProperties examScoreTemplateProperties;

    @Override
    public List<ExamScoreImportExcelVO> getTemplateData() {
        String filePath = examScoreTemplateProperties.getFilePath();
        if (!StringUtils.hasText(filePath)) {
            log.warn("[getTemplateData][文件路径为空，返回空列表]");
            return new ArrayList<>();
        }

        File file = new File(filePath);
        if (!file.exists() || !file.isFile()) {
            log.warn("[getTemplateData][文件不存在或不是文件：{}]", filePath);
            return new ArrayList<>();
        }

        try (FileInputStream inputStream = new FileInputStream(file)) {
            List<ExamScoreImportExcelVO> templateData = EasyExcel.read(inputStream, ExamScoreImportExcelVO.class, null)
                    .autoCloseStream(false)
                    .doReadAllSync();
            log.info("[getTemplateData][成功从文件读取模板数据，数量：{}]", templateData.size());
            return templateData;
        } catch (IOException e) {
            log.error("[getTemplateData][读取模板文件失败：{}]", filePath, e);
            return new ArrayList<>();
        }
    }

    @Override
    public String getSourceType() {
        return "file";
    }
}